package Inits

import (
	"fmt"
	"github.com/redis/go-redis/v9"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
	"video_-chat/conf"
	"video_-chat/global"
	"video_-chat/internal/moble"
	"video_-chat/ticker"
)

func Inits() {
	MysqlLink()
	RedisLink()
	go LoginLog()
	go ticker.Delete()
	zapInit()
}

func zapInit() {
	global.Logger, _ = zap.NewProduction()
}

func LoginLog() {
	moble.LoginLog{}.LogSet()
	ticker := time.NewTicker(24 * time.Hour)
	for _ = range ticker.C {
		moble.LoginLog{}.LogSet()
	}
}

func RedisLink() {
	global.RDB = redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%s", conf.AppConfig.Redis.Host, conf.AppConfig.Redis.Port),
		Password: conf.AppConfig.Redis.Password,
		DB:       0,
	})
	if err := global.RDB.Set(global.Ctx, "trys", "ok", 0).Err(); err != nil {
		panic(err)
	}
	fmt.Println("redis link ok")
}

func MysqlLink() {
	var err error
	var Dsn = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", conf.AppConfig.Mysql.User, conf.AppConfig.Mysql.Password, conf.AppConfig.Mysql.Host, conf.AppConfig.Mysql.Port, conf.AppConfig.Mysql.Database)
	fmt.Println("Dsn", Dsn)
	global.DB, err = gorm.Open(mysql.Open(Dsn))
	if err != nil {
		panic("failed to connect database")
	}
	fmt.Println("MySQL Connected")
}
